<?php
class ModelToolCron extends Model {
    public function getCron($cron_id, $now_time){
        $query=$this->db->query("SELECT * FROM " . DB_PREFIX . "community_crons WHERE " . ($cron_id ? "cron_id='" . (int)$cron_id . "'" : "available>'0' AND next_run<='" . $now_time . "'") . " ORDER BY next_run LIMIT 1");

        return $query->row;
    }

    public function executeCron($file){
        if(!@include $file) {
            return FALSE;
        }

        return TRUE;
    }

    public function setNextRunTime($cron_id, $next_run, $now_time){
        $sql="UPDATE " . DB_PREFIX . "community_crons SET last_run='" . $now_time . "', next_run='" . $next_run . "'";

        if($next_run <= time()){
            $sql.=", available='0'";
        }

        $sql.=" WHERE cron_id='" . $cron_id . "'";

        $this->db->query($sql);
    }

    public function getNextRunCron(){
        $query=$this->db->query("SELECT next_run FROM " . DB_PREFIX . "community_crons WHERE available>'0' ORDER BY next_run LIMIT 1");

        if($query->row){
            return $query->row['next_run'];
        }else{
            return FALSE;
        }
    }

    public function logCron($cron, $now_time, $fail=FALSE){
        $this->load->language('module/cron');

        if($fail){
            $info=sprintf($this->language->get('text_cron_fail'),$cron['name']);
        }else{
            $info=sprintf($this->language->get('text_cron_run'),$cron['name']);
        }

        $this->db->query("INSERT INTO " . DB_PREFIX . "community_cron_log SET cron_id='" . (int)$cron['cron_id'] . "', logtime='" . $now_time . "', log='" . $this->db->escape($info) . "'");
    }
}
?>